import connection from '../../utils/db.js'
import requestCodes from '../../config/responseCodes.js'

// 统一处理返回结果
const handleSqlAction = function (err, result, res, req, reject) {
  if(err) {
    console.log('[SELECT ERROR] - ', err.message)
    reject(err.message || '请求出错')
    return;
  }
  res.send({
    code: requestCodes.success,
    message: '请求成功',
    data: result
  })
}

// 查 Retrieve
export const handler = (req, res) => {
  const sql = 'SELECT * FROM websites'
  return new Promise((resolve, reject) => {
    connection.queryPool(sql, null, (err, result) => {
      handleSqlAction(err, result, res, req, reject)
    })
  })
}

// 增 Create
export const handlerAdd = (req, res) => {
  const sql = `
    INSERT INTO websites (name, url, alexa, country)
    SELECT '${req.body.name}', '${req.body.url}', '${Math.round(Math.random()*99999)}', '${req.body.country}'
  `
  return new Promise((resolve, reject) => {
    connection.queryPool(sql, null, (err, result) => {
      handleSqlAction(err, result, res, req, reject)
    })
  })
}

// 删 Delete
export const handlerDelete = (req, res) => {
  const sql = `
    DELETE FROM websites
    WHERE Id=${req.body.Id}
  `
  return new Promise((resolve, reject) => {
    connection.queryPool(sql, null, (err, result) => {
      handleSqlAction(err, result, res, req, reject)
    })
  })
}

// 改 Update
export const handlerUpdate = async (req, res) => {
  const sql = `
    DELETE FROM websites
    WHERE Id=${req.body.Id}
  `
  return new Promise((resolve, reject) => {
    connection.queryPool(sql, null, (err, result) => {
      handleSqlAction(err, result, res, req, reject)
    })
  })
}